<template>
  <continer :isNoTabs="true" :isShowTree="true" :contentHeight="'calc(100% - 96px)'">
    <template slot="tree">
      <agentTree
        ref="agentTreeRef"
        :companyName="companyName"
        :schemaData="schemaData"
        @editOrAdd="editOrAddAgentTree"
        @delFun="delAgentTreeFun"
        @import="importFun"
        @handleNodeClick="handleNodeClick">
      </agentTree>
    </template>
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="queryAgentList(null, null, false)"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button slot="reference" size="mini" style="padding: 6px 12.3px"  v-popover:popover>
        <i class="V7_iconfont V7_iconV7tubiao_shaixuan"  style="font-size: 12px"></i>
        更多
      </el-button>
       <el-popover
          ref="popover"
          placement="bottom"
          width="400"
          trigger="click"
          popper-class='agentPopper'
          v-model="form.moreSearch"
          >
          <div>
            <el-form :inline="true" class="myForm" size='mini' label-position='top' ref="form" :model="form" label-width="80px">
              <el-form-item class="var-item" label="版本">
                <el-select size='mini' filterable multiple collapse-tags clearable v-model="form.agentVersion" style="width: 100%;" >
                  <el-option  v-for="item in licenceList" :key="item.value" :label="item.name" :value="item.licenceId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="var-item"  label="角色">
                <el-select size='mini' filterable multiple collapse-tags clearable v-model="form.roles" style="width: 100%;" >
                  <el-option  v-for="item in roleList" :key="item.value" :label="item.name" :value="item._id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="状态" class="var-item">
                <el-select size='mini'  clearable v-model="form.status" >
                  <el-option  v-for="item in angetStatusData" :key="item.name" :label="item.name" :value="item._id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="手机号码" class="var-item">
                <el-input size='mini' placeholder="请输入" clearable v-model="form.mobile"></el-input>
              </el-form-item>
              <el-form-item label="sip号" class="var-item">
                <el-input placeholder="请输入" clearable v-model="form.sipNumber"></el-input>
              </el-form-item>
              <el-form-item label="外显号" class="var-item">
                <el-input placeholder="请输入" clearable v-model="form.displayNumber"></el-input>
              </el-form-item>
              <el-form-item label="座席昵称" class="var-item">
                <el-input placeholder="请输入" clearable v-model="form.agentNickname"></el-input>
              </el-form-item>
            </el-form>
            <el-button size="mini" style="float: right"  @click="queryAgentList(true, null, true)" type="primary">检索</el-button>
          </div>
        </el-popover>
      <el-button type="primary" style="margin-left: 10px" size="mini" @click="queryAgentList">查询</el-button>
      <!-- <el-button size="mini" @click="importFun">导入</el-button> -->
      <el-button size="mini" @click="addBtnFun" v-functions="['user_management_insert']">新增</el-button>
    </template>
    <template slot="content">
      <!-- 表格 -->
      <instiutionTable ref="tableRef"
        class="instiutionTableBox"
        :pages="agentInfoTablePages"
        :instiutionTableData="agentInfoTableData"
        :instiutionTableHeader="agentInfoTableHeader"
        :batchOperate="batchOperate"
        @batchClick="batchClick"
        @sizeChange="sizeChange"
        @checkHeadersChange="checkHeadersChange"
        @batchEnableAgentFun="batchEnableAgentFun"
        @currentChange="currentChangeFun">
      </instiutionTable>
      <!-- 右侧抽屉 -->
      <drawer
        class="agent-drawer"
        direction="rtl"
        :title="drawer.title"
        :drawer="drawer.isShow"
        @save="agentInfoConfirm"
        @cancelFun="cancelFun('addOrEdit')"
        @closeDraw="cancelFun('addOrEdit')">
        <template slot="column">
          <FunTab
            :tabs="tabs"
            :value="drawer.childTabActiveName"
            @input="setFunTabName"
          ></FunTab>
          <!-- 基本信息 -->
          <div class="agent-contain-box">
            <div v-show="drawer.childTabActiveName === 'baseInfo'">
              <baseInfo
                ref="agentBaseInfo"
                :editionData="licenceList"
                :sipNumberList="sipNumberList"
                :peerData="getQueueList">
              </baseInfo>
            </div>
            <div v-show="drawer.childTabActiveName === 'schemaConfig'">
              <schemaConfig :schemaOpt="schemaData" :agentListArr="agentListArr" ref="schema"></schemaConfig>
            </div>
            <div v-show="drawer.childTabActiveName === 'callCenterConfig'">
              <callCenterConfig :numbersData="outlineNumData" ref="callCenter"></callCenterConfig>
            </div>
            <div v-show="drawer.childTabActiveName === 'webChatConfig'">
              <webchatConfigBox ref="webchatConfigRef"></webchatConfigBox>
            </div>
            <div v-show="drawer.childTabActiveName === 'businessConfig'">
              <businessConfig ref="businessConfigRef"></businessConfig>
            </div>
          </div>
        </template>
      </drawer>
      <drawer
        class="import-drawer"
        direction="rtl"
        size="40%"
        :title="importDrawer.title"
        :drawer="importDrawer.isShow"
        @save="importSaveFun"
        @cancelFun="cancelFun('import')"
        @closeDraw="cancelFun('import')">
        <template slot="column">
          <div class="importTop">
            <div class="clearfix">
              <img :src="uploadImg" class="fl"/>
              <div class="fl" style="marginLeft: 20px">
                <p>请下载模板并按照模板格式填写数据后再进行导入，<br>单次带入只读取第一个sheet中的数据。</p>
                <div>
                  <el-button size="mini" class="fl importBtn">
                    <a href="/temp/agentTemp.xlsx" download="批量导入座席模板">下载模板</a>
                  </el-button>
                  <el-upload
                    class="upload-demo"
                    ref="importAgent"
                    accept=".xls, .xlsx"
                    :action="importUrl"
                    :limit='1'
                    :on-success="handleImportSuccess"
                    :before-upload="beforeUpload"
                    :on-remove="handleRemove"
                    :headers="{
                      sessionid: accountObj.userId,
                      loginToken: accountObj.loginToken
                    }">
                    <el-button type="primary" size="mini" class="fl" style="marginLeft: 10px">上传文件</el-button>
                  </el-upload>
                </div>
              </div>
            </div>
          </div>
          <div class="content">
            <h5><span class="V7_iconfont V7_iconV7tubiao_zhongyaoxiaoxi"></span>小贴士</h5>
            <ul>
              <li>批量导入为批量更增，座席拥有多个角色或者部门须用英文,分隔。</li>
              <li>更增规则：</li>
              <li>模板中存在、系统中也存在的座席，更新座席在模板文件中指定的字段值</li>
              <li>模板中存在、系统中不存在的成员，执行添加操作</li>
              <li>系统中存在、文件中不存在的成员，保持不变</li>
              <li>系统中存在、文件中为空的对应数据，数据清空</li>
              <li>模板说明：</li>
              <li v-for="(item, index) in importTitle" :key="index">{{item}}</li>
            </ul>
          </div>
        </template>
      </drawer>
    </template>

  </continer>
</template>

<script lang="ts">
import { Component, Ref, Mixins } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import FunTab from '@/components/cardLayout/FunTab.vue'
import baseInfo from '@/views/config/agent/baseInfo.vue'
import callCenterConfig from '@/views/config/agent/callCenterConfig.vue'
import webchatConfigBox from '@/views/config/agent/webchatConfig.vue'
import drawer from '@/common/views/drawer/index.vue'
import agentTree from '@/views/config/agent/agentTree.vue'
import businessConfig from './businessConfig.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import schemaConfig from '@/views/config/agent/schemaConfig.vue'
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
import { checkPermission } from '@/utils/directive'
import { commonAction, deepClone, regexPass } from '@/utils/common'
import { Base64 } from 'js-base64'
import NodeRSA from 'node-rsa'
import oprateMixin from '@/mixins/dialogOprate'
// eslint-disable-next-line no-unused-vars
import { Form as ElForm } from 'element-ui'
import { CommonModule } from '@/store/modules/common'
interface InterStatus {
  [x: string]: any
  status: 'enable' | 'disable'
}
export function handleTreeData (data: any, newObj?: any, str?: any, ids?: any) {
  for (let i = 0; i < data.length; i++) {
    let newStr = str
    let newIds: any = deepClone(ids)
    if (newStr) {
      newStr += '/' + data[i].name
    } else {
      newStr = data[i].name
    }
    if (newIds) {
      newIds.push(data[i]._id)
    } else {
      newIds = [data[i]._id]
    }
    data[i].name = newStr
    data[i].ids = newIds
    newObj[data[i]._id] = { name: data[i].name, _id: data[i]._id, ids: data[i].ids }
    const options = deepClone(data[i].children)
    if (options && options.length > 0) {
      handleTreeData(options, newObj, newStr, newIds)
    }
  }
  return newObj
}
@Component({
  name: 'Agent',
  components: {
    businessConfig,
    QuickSearch,
    baseInfo,
    callCenterConfig,
    webchatConfigBox,
    instiutionTable,
    drawer,
    continer,
    FunTab,
    agentTree,
    schemaConfig
  }
})
export default class Agent extends Mixins(oprateMixin) {
  [x: string]: any
  @Ref() private readonly tableRef!: instiutionTable
  @Ref() private readonly agentBaseInfo !: baseInfo
  @Ref() private readonly callCenter !: callCenterConfig
  @Ref() private readonly webchatConfigRef !: webchatConfigBox
  @Ref() private readonly schema !: schemaConfig

  private quickSearchForm: any = {}
  private form: any = {
    moreSearch: false,
    agentVersion: [],
    roles: []
  }

  private importTitle = [
    '1.工号：3~6位数字，是唯一标示不能重复；',
    '2.座席名称：至多40个字符。座席昵称，至多40个字符；',
    '3.手机号码：不能重复；',
    '4.SIP号：3~6位数字，请填入系统中已创建并且未被绑定的SIP号；',
    '5.版本：请填入正确的版本名称；',
    '6.角色：请填入系统中已创建的角色名称，注意需要对应版本；',
    '7.所属技能组：请填入系统中已创建的技能组名称；',
    '8.所属部门和主管部门：请正确填入部门名称，部门层级间用英文/分隔，支持多个部门；',
    '9.外显号码：请填入系统中的外显号码，不填写则为空；',
    '10.整理时长：请填入0~999之间的正整数。如不填写默认使用30；',
    '11.会话上限：范围为1~200，最大上限需要大于最小上限。如不填写默认使用1和10。',
    '12.导入座席的登录密码默认为：123456Abc请及时修改。',
    '13.导入座席数量如果超出套餐座席最大数，超出部分不执行导入。'
  ]

  private accountObj = {
    account: '',
    userId: '',
    loginToken: ''
  }

  private tabs: object[] = [
    { label: '基本信息', name: 'baseInfo' },
    { label: '部门设置', name: 'schemaConfig' },
    { label: '工单设置', name: 'businessConfig' }
  ]

  private treeDataObj = []

  private uploadImg = require('../../../assets/img/uploadFile.png')

  private batchOperate = [ // 批量操作设置
    { name: '批量启用', action: 'batchEnableAgentFun', _id: 'user_management_batch_enableOrDisable' },
    { name: '批量停用', action: 'batchDisableAgentFun', _id: 'user_management_batch_enableOrDisable' },
    { name: '列表下座席导出', action: 'bulkExport', _id: 'user_management_batch_export' }
  ]

  private drawer = {
    isShow: false, // 右侧抽屉是否显示
    title: '添加座席', // 右侧抽屉标题
    childTabActiveName: 'baseInfo' // 当前选中的tab
  }

  private importDrawer = { // 导入抽屉
    isShow: false,
    title: '导入座席'
  }

  public statusMap = {
    enable: { name: '启用', iconClass: 'green-color V7_iconV7tubiao_dian' },
    disable: { name: '停用', iconClass: 'red-color V7_iconV7tubiao_dian' },
    locked: { name: '锁定', iconClass: 'red-color V7_iconV7tubiao_dian' }
  }

  private agentInfoTableHeader: any[] = [ // 座席信息表头
    { type: 'select' },
    { label: '座席名称', prop: 'agentName', isSort: true },
    { label: '座席工号', prop: 'agentNumber', isSort: true },
    { label: '部门', prop: 'departName' },
    { label: '上级', prop: 'leaderName' },
    { label: '角色', prop: 'roleName', isSort: true },
    { label: '状态', prop: 'status', isDictionary: true, dictionary: this.statusMap, showStatusIcon: true, isSort: true },
    { label: '版本', prop: 'uversionName' }
    // { label: '最后更新时间', prop: 'updateTime', isSort: true }
    // { type: 'customHeader' }
  ]

  private agentInfoTableData = [] // 座席信息表格信息

  private agentInfoTablePages = { // 翻页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private licenceList: any = [] // 版本数据

  private outlineNumData: any = [] // 外显号数据

  private filepath: string = ''

  private sipNumberList: any[] = [] // sip号

  private companyName: string = '' // 公司名称

  private schemaData: any = [] // 组织架构树结构

  private departmentIdList = ''

  private importFun () { // 导入弹窗事件
    this.importDrawer.isShow = true
  }

  private setFunTabName (name) {
    this.drawer.childTabActiveName = name
  }

  private batchClick (action, selectList) {
    this[action](selectList)
  }

  private addBtnFun () { // 添加事件
    this.open()
    this.drawer.isShow = true
    this.drawer.title = '添加座席'
    this.drawer.childTabActiveName = 'baseInfo'
    this.getSipNumberList('add', null) // 获取最新的已注册未绑定的sip号
    this.$nextTick(() => {
      this.agentBaseInfo.setAgentBaseInfoData()
      this.callCenter.setCallCenterConfigData()
      this.webchatConfigRef.setWebchatConfigData()
      this.schema.setSchemaConfigData();
      (this.$refs as any).businessConfigRef.setBusinessData()
    })
  }

  private checkHeadersChange (checkList) {
    this.$set(this, 'agentInfoTableHeader', checkList)
  }

  private cancelFun (type: string) { // 基本信息取消事件
    if (type === 'addOrEdit') { // 新增or编辑座席
      if (this.agentBaseInfo) {
        this.agentBaseInfo.setAgentBaseInfoData()
      }
      if (this.callCenter) {
        this.callCenter.setCallCenterConfigData()
      }
      if (this.webchatConfigRef) {
        this.webchatConfigRef.setWebchatConfigData()
      }
      if (this.schema) {
        this.schema.setSchemaConfigData()
      }
      this.drawer.childTabActiveName = 'baseInfo'
      this.drawer.isShow = false
      this.open()
    } else if (type === 'import') { // 导入抽屉
      this.importDrawer.isShow = false
      this.filepath = ''
      const epxortRef: any = this.$refs.importAgent
      if (epxortRef) {
        epxortRef.clearFiles()
      }
    }
  }

  private importSaveFun () { // 座席导入保存事件
    if (!this.filepath) {
      this.$message.error('请选择文件上传')
      return
    }
    const actionData = {
      url: '/base/action/user/import/task/create',
      method: 'post',
      data: {
        type: 'agent',
        accountId: this.accountObj.account,
        createUser: this.accountObj.userId,
        filepath: this.filepath
      }
    }
    const epxortRef: any = this.$refs.importAgent
    epxortRef.clearFiles()
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.filepath = ''
        this.importDrawer.isShow = false
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导入任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
      }
    })
  }

  private jumpToTransmissionCenter () {
    this.$router.push('/transmission_center/index/tx_import_task?taskModule=agent')
  }

  private agentInfoConfirm () { // 基本信息保存事件
    const formRef = this.agentBaseInfo.$refs.agentBaseInfoForm as ElForm
    formRef.validate(valide => {
      if (valide) {
        const callCenterData = deepClone(this.callCenter.callCenterConfigForm)
        const webchatConfig = deepClone(this.webchatConfigRef.webchatConfigForm)
        const departmentConfig = deepClone(this.schema.schemaConfigForm)
        const callFromRef = this.callCenter.$refs.callCenterConfigForm as ElForm
        callFromRef.validate(valide2 => {
          if (valide2) {
            const agentBaseInfoData = deepClone(this.agentBaseInfo.agentBaseInfoForm)
            callCenterData.restTime = callCenterData.restTime + ''
            const sendData = { ...agentBaseInfoData, ...callCenterData, webchatConfig, departmentConfig }
            const { password } = sendData
            const publicKey = this.$store.state.common ? this.$store.state.common.preLogin.pk : ''
            const pk = Base64.decode(publicKey)
            const key = new NodeRSA(pk)
            let sendUrl = '/base/action/user/create'
            let successMsg = '创建座席成功'
            if (sendData._id !== '') {
              sendUrl = '/base/action/user/update'
              successMsg = '更新座席成功'
              if (password !== '') {
                if (!regexPass(password, password)) {
                  this.$message.error('密码必须大于等于8位，并包含数字，小写字母，大写字母，特殊字符中的至少3种，特殊字符不能是%、&、+、\'、\\"、<、>、=')
                  return false
                }
                const encrypted = key.encrypt(password, 'base64')
                sendData.password = encrypted
              } else {
                delete sendData.password
              }
            } else {
              delete sendData._id
              if (password === '') {
                this.$message.error('请输入密码')
                return false
              } else if (!regexPass(password, password)) {
                this.$message.error('密码必须大于等于8位，并包含数字，小写字母，大写字母，特殊字符中的至少3种，特殊字符不能是%、&、+、\'、\\"、<、>、=')
                return false
              }
              const encrypted = key.encrypt(password, 'base64')
              sendData.password = encrypted
            }
            const actionData = { url: sendUrl, method: 'POST', data: { ...sendData } }
            organizationConfigModule.organizationCommonAction(actionData).then(res => {
              if (res && res.success) {
                this.drawer.isShow = false
                const params = Object.assign({}, (this.$refs as any).businessConfigRef.busConfigForm, { agentId: res.data._id })
                const data: any = { url: '/server-flow/action/agent/config/order', method: 'post', data: params }
                commonAction(data).then((res1) => {
                  if (res1.success) {
                    this.$message.success('修改座席成功')
                  }
                });
                this.queryAgentList(sendData._id === '' ? 'add' : null)
                if (!sendData._id) {
                  this.$addOneCache('userList', res.data, true)
                } else {
                  this.$updateCache('userList', res.data, '_id', true)
                }
                this.$message.success(successMsg)
                if (this.agentBaseInfo) {
                  this.agentBaseInfo.setAgentBaseInfoData()
                }
                if (this.callCenter) {
                  this.callCenter.setCallCenterConfigData()
                }
                if (this.webchatConfigRef) {
                  this.webchatConfigRef.setWebchatConfigData()
                }
                if (this.schema) {
                  this.schema.setSchemaConfigData()
                }
              }
            })
          }
        })
      }
    })
  }

  private editOrAddAgentTree () { // 添加或编辑组织架构
    this.getTreeData()
  }

  private delAgentTreeFun () { // 删除组织架构
    this.getTreeData()
  }

  private async getTreeData () { // 查询组织架构数据
    const result: any = await CommonModule.getDepartmentTree()
    this.schemaData = result.tree || []
    this.companyName = result.companyName || ''
    this.treeDataObj = handleTreeData(result.tree, {})
  }

  private handleNodeClick (obj: string) {
    this.departmentIdList = obj
    this.queryAgentList(null, obj)
  }

  private moreSearchFlag = false

  private queryAgentList (addSuccess?: any, obj?: string, flag?: boolean) { // 列表查询
    if (flag === true) {
      this.moreSearchFlag = true
    }
    if (flag === false) {
      this.moreSearchFlag = false
    }
    if (addSuccess) { // 新增回到第一页
      this.agentInfoTablePages.current = 1
    }
    let sendData: any = {
      departmentIdList: this.departmentIdList ? [this.departmentIdList] : [],
      page: this.agentInfoTablePages.current,
      limit: this.agentInfoTablePages.pageSize,
      ...this.quickSearchForm.form,
      moreSearch: false
    }
    if (this.moreSearchFlag) {
      sendData = Object.assign({}, {
        departmentIdList: this.departmentIdList ? [this.departmentIdList] : [],
        page: this.agentInfoTablePages.current,
        limit: this.agentInfoTablePages.pageSize
      }, this.form, { moreSearch: true })
    }
    const actionData = { url: '/base/action/user/query', method: 'POST', data: { ...sendData } }
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res.list) {
        const list = res.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.agentInfoTablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.agentInfoTablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.agentInfoTablePages.current = page
            this.queryAgentList()
            return false
          }
        }
        if (list.length > 0) {
          list.forEach(item => {
            const uversionItem = this.licenceList.find((licenceItem: any) => licenceItem.licenceId === item.agentVersion)
            const roleArr = item.roles || []
            let roleStr = ''
            roleArr.forEach((item2: any) => {
              const roleItem: any = this.$store.state.common.publicCache.roleListObj[item2]
              if (roleItem) {
                roleStr += `${roleItem.name}、 `
              }
            })
            item.uversionName = (uversionItem && uversionItem.name) || '--'
            roleStr = roleStr.slice(0, roleStr.length - 2)
            item.roleName = roleStr
            if (item.departmentConfig && item.departmentConfig.leaderId) {
              const currentAgent = CommonModule.publicCache.userListObj[item.departmentConfig.leaderId]
              if (currentAgent) {
                item.leaderName = currentAgent.name
              } else {
                item.leaderName = '--'
              }
            } else {
              item.leaderName = '--'
            }
            if (item.departmentConfig && item.departmentConfig.departmentIdList && item.departmentConfig.departmentIdList.length > 0) {
              let departName: any = ''
              item.departmentConfig.departmentIdList.forEach(departItem => {
                const currentDepart: any = this.treeDataObj[departItem]
                departName += `${(currentDepart && currentDepart.name) || ''}、 `
              })
              departName = departName.slice(0, departName.length - 2)
              item.departName = departName
            } else {
              item.departName = '--'
            }
          })
        }
        this.agentInfoTableData = res.list
        this.agentInfoTablePages.total = res.count || 0
      }
    })
  }

  private bulkExport (selectedArr) { // 批量导出
    let sendData: any = {}
    if (Array.isArray(selectedArr)) {
      sendData = { ids: selectedArr }
    } else {
      sendData = {
        condition: {
          ...this.quickSearchForm.form,
          moreSearch: false,
          departmentIdList: this.departmentIdList ? [this.departmentIdList] : []
        }
      }
      if (this.moreSearchFlag) {
        sendData = {}
        sendData.condition = Object.assign({}, this.form, { moreSearch: true, departmentIdList: this.departmentIdList ? [this.departmentIdList] : [] })
      }
    }
    commonAction({ url: '/base/action/user/export', method: 'post', data: sendData }).then(res => {
      if (res.success) {
        this.$message.success('导出任务创建成功')
      }
    })
  }

  private batchDisableAgentFun (selectedArr: any) { // 批量停用
    this.batchEnableAgentFun(selectedArr, 'disable')
  }

  private batchEnableAgentFun (selectedArr: any, disable?: string) { // 批量启用
    let sendData: any = {}
    if (typeof selectedArr === 'object') { // 单个操作，传ids
      sendData = { ids: selectedArr || [], departmentIdList: this.departmentIdList ? [this.departmentIdList] : [] }
    } else { // 全选传查询条件
      sendData = {
        condition: {
          page: this.agentInfoTablePages.current,
          limit: this.agentInfoTablePages.pageSize,
          ...this.quickSearchForm.form,
          moreSearch: false,
          departmentIdList: this.departmentIdList ? [this.departmentIdList] : []
        }
      }
      if (this.moreSearchFlag) {
        sendData = {}
        sendData.condition = Object.assign({}, this.form, { moreSearch: true })
      }
    }
    const sendUrl = disable === 'disable' ? '/base/action/user/batch/disable' : '/base/action/user/batch/enable'
    const statusName = disable === 'disable' ? '停用' : '启用'
    const actionData = { url: sendUrl, method: 'POST', data: sendData }
    this.$confirm(`确定要批量${statusName}该座席吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      organizationConfigModule.organizationCommonAction(actionData).then(res => {
        if (res) {
          this.$message.success('批量变更座席状态成功')
          this.tableRef.cancelSelectFun() // 关闭批量操作栏
          this.queryAgentList()
        }
      })
    })
  }

  private handleState (obj: InterStatus) { // 停用||启用
    const statusMap = { disable: 'enable', enable: 'disable' }
    const status = statusMap[obj.status]
    const statusName = status === 'enable' ? '启用' : '停用'
    const sendUrl = status === 'enable' ? '/base/action/user/enable' : '/base/action/user/disable'
    const sendData = { url: sendUrl, data: { _id: obj._id }, method: 'POST' }
    this.$confirm(`确定要${statusName}该座席吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      organizationConfigModule.organizationCommonAction(sendData).then(res => {
        this.$message.success('变更座席状态成功')
        this.queryAgentList()
      })
    })
  }

  private unLockFun (obj: any) { // 座席解锁
    const sendUrl = '/base/action/user/unlock'
    const sendData = { url: sendUrl, data: { _id: obj._id }, method: 'POST' }
    this.$confirm('确定要解锁该座席吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      organizationConfigModule.organizationCommonAction(sendData).then(res => {
        this.$message.success('解锁座席成功')
        this.queryAgentList()
      })
    })
  }

  private sizeChange (size: number) {
    this.agentInfoTablePages.pageSize = size
    this.queryAgentList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.agentInfoTablePages.current = page
    this.queryAgentList()
  }

  private getOrderMsg (id: string) {
    const data: any = { url: '/server-flow/action/agent/config/order?agentId=' + id, method: 'get' }
    commonAction(data).then((res) => {
      if (res.success) {
        (this.$refs as any).businessConfigRef.setBusinessData(res.data)
      }
    })
  }

  private handleEdit (obj: any) { // 表格编辑
    this.drawer.isShow = true
    this.drawer.title = '编辑座席'
    this.drawer.childTabActiveName = 'baseInfo'
    this.getSipNumberList('edit', obj) // 获取最新的已注册未绑定的sip号
    this.getOrderMsg(obj._id)
    this.$nextTick(() => {
      if (this.agentBaseInfo) {
        this.agentBaseInfo.setAgentBaseInfoData(obj)
      }
      if (this.callCenter) {
        this.callCenter.setCallCenterConfigData(obj)
      }
      if (this.webchatConfigRef) {
        this.webchatConfigRef.setWebchatConfigData(obj)
      }
      if (this.schema) {
        if (obj.departmentConfig && obj.departmentConfig.departmentIdList.length > 0) {
          const departArr: any = []
          obj.departmentConfig.departmentIdList.forEach(item => {
            const currentDepart: any = this.treeDataObj[item]
            if (currentDepart) {
              departArr.push(currentDepart.ids)
            }
          })
          obj.departmentConfig.departmentIdList = deepClone(departArr)
        }
        this.schema.setSchemaConfigData(obj.departmentConfig || {})
      }
    })
  }

  private getSipNumberList (type: string, obj: any) { // 获取已注册未绑定的sip号（每次从后台获取最新的）
    const actionData = { url: '/call/action/general/query', method: 'POST', data: { types: ['availableSipNumberList'] } }
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res && res.success) {
        const resList = res.availableSipNumberList || []
        if (type === 'edit' && obj.sipNumber) { // 编辑的时候 && 当前座席绑定过sip号码，要把当前选中的加上查回来的列表
          resList.unshift({ number: obj.sipNumber, numberName: obj.sipNumber })
        }
        resList.unshift({ number: '', numberName: '请选择' })
        this.sipNumberList = resList
      }
    })
  }

  private handleImportSuccess (res: any) {
    if (res && res.success && res.data) {
      this.filepath = res.data.path
    }
  }

  private beforeUpload (file: any) { // 上传前验证文件合法性
    const fileName = /[^.]+$/.exec(file.name.replace(/\s/g, ''))
    if (fileName && (fileName[0] !== 'xls' && fileName[0] !== 'xlsx')) {
      this.$message({ message: '仅支持上传xls,xlsx文件', type: 'error' })
      return false
    }
  }

  private deactivated () {
    this.drawer.isShow = false
  }

  private handleRemove () {
    this.filepath = ''
  }

  get roleList () {
    return this.$store.state.common.publicCache.roleList || []
  }

  get importUrl () {
    return '/upload?accountId=' + this.accountObj.account + '&module=agent'
  }

  get agentListArr () {
    const agents = deepClone(CommonModule.publicCache.userListObj)
    const agentsArr: any = []
    for (const i in agents) {
      agentsArr.push({ _id: agents[i]._id, name: agents[i].name })
    }
    return agentsArr
  }

  get getQueueList () {
    return this.$store.state.common.publicCache.queueList || []
  }

  private angetStatusData = [ // 座席状态
    { name: '停用', _id: 'disable' },
    { name: '启用', _id: 'enable' },
    { name: '锁定', _id: 'locked' }
  ]

  private mounted () {
    this.$getCache('/base/action/general/cache/query', ['licenceList', 'roleList', 'userList'], true).then(async (data: any) => {
      this.licenceList = data.licenceList || []
      // this.roleList = data.roleList || []
      const angetStatusData = [ // 座席状态
        { name: '停用', _id: 'disable' },
        { name: '启用', _id: 'enable' },
        { name: '锁定', _id: 'locked' }
      ]
      this.quickSearchForm = {
        form: {
          agentName: '',
          noDepartment: false
        },
        advSearchOptions: [ // 高级搜索数据
          { label: '座席名称/工号', inputType: 'input', placeholder: '请输入座席名称/工号', name: 'agentName' },
          // { label: '状态', inputType: 'select', clearable: true, selectData: angetStatusData, name: 'status' },
          // { label: '版本', inputType: 'ele-select', selectData: this.licenceList, multiple: true, name: 'agentVersion', defaultProp: { label: 'name', value: 'licenceId' }, noDisabled: true },
          // { label: '角色', inputType: 'select', selectData: this.roleList, multiple: true, name: 'roles' },
          { label: '', inputType: 'checkbox', name: 'noDepartment', checkboxName: '仅未分配座席' }
        ]
      }
      this.getTreeData()
      await this.queryAgentList()
    })
    const actionData = { url: '/call/action/general/query', method: 'POST', data: { types: ['displayNumerList'] } }
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res) {
        if (res.displayNumerList) {
          this.outlineNumData = deepClone(res.displayNumerList)
        }
      }
    })
  }

  private beforeMount () {
    let handlers: any[] = []
    if (checkPermission(null, { value: ['user_management_edit'] })) {
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.handleEdit(scope.row) })
    }
    if (checkPermission(null, { value: ['user_management_enableOrDisable'] })) {
      handlers = [...handlers,
        ...[
          { name: '停用', className: 'danger', field: 'status', status: 'enable', handleFn: (scope: any) => this.handleState(scope.row) },
          { name: '启用', field: 'status', status: 'disable', handleFn: (scope: any) => this.handleState(scope.row) }
        ]
      ]
    }
    if (checkPermission(null, { value: ['user_management_unlock'] })) {
      handlers = [...handlers,
        ...[
          { name: '解锁', field: 'status', status: 'locked', handleFn: (scope: any) => this.unLockFun(scope.row) }
        ]
      ]
    }
    if (checkPermission(null, { value: ['user_call_config'] }, 'limits')) {
      this.tabs.push({ label: '呼叫中心配置', name: 'callCenterConfig' })
    }
    if (checkPermission(null, { value: ['user_call_config'] }, 'limits')) {
      this.tabs.push({ label: '在线客服配置', name: 'webChatConfig' })
    }
    this.batchOperate = this.batchOperate.filter(item => checkPermission(null, { value: [item._id] })) // 过滤批量操作的权限
    this.agentInfoTableHeader.push({ label: '操作', width: 100, handlers })
    this.accountObj.account = (this.$store as any).state.common.session.account._id
    this.accountObj.userId = (this.$store as any).state.common.session.user._id
    this.accountObj.loginToken = (this.$store as any).state.common.session.user.loginToken
  }
}
</script>

<style lang="stylus" scoped>
.var-item
  width: 47%
.agent-drawer
  >>> .drawer-contain
    height auto
  .agent-contain-box
    height calc(100vh - 174px)
    overflow auto
    padding-right 20px
.import-drawer
  .importTop
    padding 36px
    background $bgc-gray
    p
      color $fc-gray2
      margin-bottom 20px
    .importBtn
      a
        color $fc-gray2
    .importBtn:hover a
      color $c-main
  .content
    margin-top 26px
    h5
      font-size 12px
      font-weight 600
    .V7_iconfont
      font-size 14px
      color $c-warn
      margin-right 5px
    li
      color $fc-gray3
      line-height 24px
.custom-search-pop
  padding 10px
/deep/.myForm .el-form-item__label
  line-height unset
</style>
<style>
.agentPopper .el-input--mini .el-input__inner {
  height: 32px!important;
  line-height: 32px;
}
</style>
